﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using University.Workshop.Business;
using University.Workshop.Model;
using University.Workshop.WinApp.Product;
using System.Collections.ObjectModel;

namespace University.Workshop.WinApp
{
    public partial class PurchaseView : Form
    {
        UserLogOn user = UserLogOn.Instance;
        Variables flag = Variables.Instance;
        PurchaseVariables variablePurchase = PurchaseVariables.Instance;
        static int indexData;
        public PurchaseView()
        {
            InitializeComponent();
            variablePurchase.IndexProductsReply = 0;
            variablePurchase.ResetReplyProducts();
            indexData = 0;
        }

        private void PurchaseView_Load(object sender, EventArgs e)
        {
            textBoxNameUserPurchase.Text = user.Name + " " + user.Surname1 + " " + user.Surname2;
            textBoxCodePurchase.Text = PurchaseController.GetPurchaseCode();
        }

        private void buttonRegisterPurchase_Click(object sender, EventArgs e)
        {
            tabControlPurchase.SelectedTab = tabPageRegisterPurchase;
        }

        private void buttonCancelRegisterPurchase_Click(object sender, EventArgs e)
        {
            tabControlPurchase.SelectedTab = tabPageMainPurchase;
        }

        private void buttonQuitPurchase_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonSearchProductPurchase_Click(object sender, EventArgs e)
        {
            flag.Product = "BrowserProductPurchase";
            FormProductView prod = new FormProductView();
            prod.ShowDialog();

            if (!string.IsNullOrEmpty(variablePurchase.ProductCode))
            {
                textBoxCodeProductPurchase.Text = variablePurchase.ProductCode;
                textBoxProductName.Text = variablePurchase.ProductName;
            }
        }

        private void buttonSearchProviderPurchase_Click(object sender, EventArgs e)
        {
            flag.Provider = "BrowserProviderPurchase";
            FormProviderView providerView = new FormProviderView();
            providerView.ShowDialog();
            textBoxProviderCode.Text = variablePurchase.ProviderCode;
            textBoxProviderName.Text = variablePurchase.ProviderName;
        }

        private void Validator_Only_Numbers_KeyPress(object sender, KeyPressEventArgs e)
        {
            Validator.ValidatorOnlyNumbers(sender, e);
        }

        private void Validator_Only_Float_KeyPress(object sender, KeyPressEventArgs e)
        {
            Validator.ValidateOnlyFloat(sender, e);
        }

        private void buttonAddItemPurchase_Click(object sender, EventArgs e)
        {
            string resp = ValidateAddProductToList();
            if (!IfProductExistsOnList(textBoxCodeProductPurchase.Text))
            {
                if (resp == "Bien")
                {
                    dataGridViewPurchase.Rows.Add();
                    dataGridViewPurchase.Rows[indexData].Cells[0].Value = textBoxCodeProductPurchase.Text;
                    dataGridViewPurchase.Rows[indexData].Cells[1].Value = textBoxPriceUnit.Text;
                    dataGridViewPurchase.Rows[indexData].Cells[2].Value = textBoxQuantity.Text;
                    dataGridViewPurchase.Rows[indexData].Cells[3].Value = (Convert.ToDouble(textBoxQuantity.Text) * Convert.ToDouble(textBoxPriceUnit.Text)).ToString();
                    indexData++;
                    textBoxPurchaseTotal.Text = (Convert.ToDouble(textBoxPurchaseTotal.Text) + (Convert.ToDouble(textBoxQuantity.Text) * Convert.ToDouble(textBoxPriceUnit.Text))).ToString();
                    textBoxCodeProductPurchase.Clear();
                    textBoxProductName.Clear();
                    textBoxQuantity.Clear();
                    textBoxPriceUnit.Clear();
                    variablePurchase.ReplyProducts[variablePurchase.IndexProductsReply] = variablePurchase.ProductCode;
                    variablePurchase.IndexProductsReply++;
                }
                else
                    MessageBox.Show(this, resp, "Error al añadir producto", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
            }
            else
                MessageBox.Show(this, "Ya existe el producto en la lista de compra!", "Repetido", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
        }

        private bool IfProductExistsOnList(string code)
        {
            bool resp = true;
            for (int i = 0; i < variablePurchase.IndexProductsReply; i++)
            {
                if (variablePurchase.ReplyProducts[i] == code)
                    return resp;
            }
            return resp = false;
        }

        private string ValidateAddProductToList()
        {
            if (string.IsNullOrEmpty(textBoxCodeProductPurchase.Text))
                return "No escogio un producto!";

            if (string.IsNullOrEmpty(textBoxPriceUnit.Text))
                return "Producto no tiene precio definido!";

            if (string.IsNullOrEmpty(textBoxQuantity.Text))
                return "No ingreso la cantidad del producto a comprar!";

            if (Convert.ToDouble(textBoxQuantity.Text, System.Globalization.CultureInfo.CurrentCulture) <= 0)
                return "No ingrese cantidades menores o iguales a cero!";

            return "Bien";
        }

        private void buttonRemoveItemPurchase_Click(object sender, EventArgs e)
        {
            if (dataGridViewPurchase.Rows.Count != 0)
            {
                dataGridViewPurchase.SelectedRows[0].Visible = false;
                textBoxPurchaseTotal.Text = (Convert.ToDouble(textBoxPurchaseTotal.Text) - (Convert.ToDouble(dataGridViewPurchase.SelectedRows[0].Cells[3].Value.ToString()))).ToString();
                for (int i = 0; i < variablePurchase.IndexProductsReply; i++)
                {
                    if (variablePurchase.ReplyProducts[i] == dataGridViewPurchase.SelectedRows[0].Cells[0].Value.ToString())
                        variablePurchase.ReplyProducts[i] = "Nothing";
                }
                indexData--;
                dataGridViewPurchase.Rows.RemoveAt(dataGridViewPurchase.SelectedRows[0].Index);
            }
        }

        private void buttonPurchaseRegister_Click(object sender, EventArgs e)
        {
            string resp = ValidatePurchaseRegistration();
            if (resp == "Registro de compra exitosa")
            {
                MessageBox.Show(this, resp, "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
                PurchaseView newPurchaseView = new PurchaseView();
                newPurchaseView.ShowDialog();
                this.Close();

            }
            else
                MessageBox.Show(this, resp, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
        }

        private string ValidatePurchaseRegistration()
        {
            if (string.IsNullOrEmpty(textBoxProviderCode.Text) || string.IsNullOrEmpty(textBoxProviderCode.Text) || string.IsNullOrEmpty(textBoxNameUserPurchase.Text))
                return "Falta llenar campos obligatorios!";

            if (textBoxPurchaseTotal.Text == "0")
                return "No hay ningun producto en la lista de venta!";

            Purchase purchase = new Purchase();
            purchase.Code = textBoxCodePurchase.Text;
            purchase.UserCode = user.Id;
            purchase.ProviderCode = textBoxProviderCode.Text;
            purchase.DatePurchase = dateTimePickerDatePurchase.Value;
            purchase.TotalAmount = textBoxPurchaseTotal.Text;
            PurchaseController.PurchaseRegister(purchase);
            Collection<PurchaseDetail> listOfProducts = ReturnAllSelectProducts();
            for (int i = 0; i < listOfProducts.Count; i++)
            {
                PurchaseController.PurchaseDetailRegister(listOfProducts[i]);
            }
            return "Registro de compra exitosa";
        }

        private Collection<PurchaseDetail> ReturnAllSelectProducts()
        {
            Collection<PurchaseDetail> list = new Collection<PurchaseDetail>();
            for (int i = 0; i < dataGridViewPurchase.Rows.Count; i++)
            {
                PurchaseDetail purchaseProduct = new PurchaseDetail();
                purchaseProduct.CodePurchase = textBoxCodePurchase.Text;
                purchaseProduct.CodeProduct = dataGridViewPurchase.Rows[i].Cells[0].Value.ToString();
                purchaseProduct.UnitPrice = Convert.ToDouble(dataGridViewPurchase.Rows[i].Cells[1].Value.ToString(), System.Globalization.CultureInfo.CurrentCulture);
                purchaseProduct.Quantity = Convert.ToInt32(dataGridViewPurchase.Rows[i].Cells[2].Value.ToString(), System.Globalization.CultureInfo.CurrentCulture);
                purchaseProduct.TotalPrice = Convert.ToDouble(dataGridViewPurchase.Rows[i].Cells[3].Value.ToString(), System.Globalization.CultureInfo.CurrentCulture);
                list.Add(purchaseProduct);
            }
            return list;
        }
   






    

 
    }
}
